# Verify conditions
ping -n 1 -w 1000 8.8.8.8 > /dev/null 2>&1
if [ $? -ne 0 ]; then
    ping -n 1 -w 1000 www.baidu.com > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo Administrator privileges and network connection are required to run this script.
        exit 1
    fi
fi

# Install software and tools
pacman -Syy
pacman -S --noconfirm base-devel cmake mingw-w64-ucrt-x86_64-gcc dos2unix git unrar unzip

# Install FFmpeg for development
FFMPEG_PACKAGE=ffmpeg-6.1.1-windows-gpl.zip
if [ ! -f $FFMPEG_PACKAGE ]; then
    echo $FFMPEG_PACKAGE not found.
    exit 1
fi

unzip $FFMPEG_PACKAGE -d /c/Windows/System32/

# Install Clang
if [ ! -d "/opt/clang-15" ]; then
    CLANG_PACKAGE=clang-15-x86-windows.zip
    if [ ! -f $CLANG_PACKAGE ]; then
        echo $CLANG_PACKAGE not found.
        exit 1
    fi

    unzip -d /opt ./$CLANG_PACKAGE
fi

# Install XTools
if [ ! -d "/opt/xtools-uni/x86-windows10" ]; then
    UNI_X86_WINDOWS10_PACKAGE=20230521-x86-windows10.zip
    if [ ! -f $UNI_X86_WINDOWS10_PACKAGE ]; then
        echo $UNI_X86_WINDOWS10_PACKAGE not found.
        exit 1
    fi

    unzip -d /opt/xtools-uni ./$UNI_X86_WINDOWS10_PACKAGE
fi

if [ ! -d "/opt/xtools-uni/x86-ubuntu2204" ]; then
    UNI_X86_UBUNTU2204_PACKAGE=20230602-x86-ubuntu2204.zip
    if [ ! -f $UNI_X86_UBUNTU2204_PACKAGE ]; then
        echo $UNI_X86_UBUNTU2204_PACKAGE not found.
        exit 1
    fi

    unzip -d /opt/xtools-uni ./$UNI_X86_UBUNTU2204_PACKAGE
fi

if [ ! -d "/opt/xtools-uni/arm-ubuntu2204" ]; then
    UNI_ARM_UBUNTU2204_PACKAGE=20230602-arm-ubuntu2204.zip
    if [ ! -f $UNI_ARM_UBUNTU2204_PACKAGE ]; then
        echo $UNI_ARM_UBUNTU2204_PACKAGE not found.
        exit 1
    fi

    unzip -d /opt/xtools-uni ./$UNI_ARM_UBUNTU2204_PACKAGE
fi

if [ ! -d "/opt/xtools-uni/x86-macos1013" ]; then
    UNI_X86_MACOS1013_PACKAGE=20230531-x86-macos1013.zip
    if [ ! -f $UNI_X86_MACOS1013_PACKAGE ]; then
        echo $UNI_X86_MACOS1013_PACKAGE not found.
        exit 1
    fi

    unzip -d /opt/xtools-uni ./$UNI_X86_MACOS1013_PACKAGE
fi

if [ ! -d "/opt/xtools-uni/arm-macos1203" ]; then
    UNI_ARM_MACOS1203_PACKAGE=20230522-arm-macos1203.zip
    if [ ! -f $UNI_ARM_MACOS1203_PACKAGE ]; then
        echo $UNI_ARM_MACOS1203_PACKAGE not found.
        exit 1
    fi

    unzip -d /opt/xtools-uni ./$UNI_ARM_MACOS1203_PACKAGE
fi

# Patch old XTools
if [ -d "/c/x-tools" ]; then
    OLD_XTOOLS_PATCH_PACKAGE=20241127_XToolsMakeRedirect.zip
    if [ -f $OLD_XTOOLS_PATCH_PACKAGE ]; then
        unzip -od /c ./$OLD_XTOOLS_PATCH_PACKAGE
    fi
fi

echo Done.
